#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>

#include "./../../inc/album.h"

// 获取指定目录下的所有文件
int findBMPByDir(char * path, file_node_p headNode)
{
    DIR * dirp = opendir(path);
    while(1) {
        struct dirent * dir_cont = readdir(dirp);
        if(dir_cont == NULL) {
            break;
        }

        char * dot = strrchr(dir_cont->d_name, '.');
        // if(dot && strcmp(dot, ".c") == 0) {
        //     *dot = '\0';
        //     file_node_create(headNode, dir_cont->d_name, path);
        // }
        if(dot && (strcmp(dot, ".bmp") == 0 || strcmp(dot, ".png") == 0 || strcmp(dot, ".jpg") == 0) ||
           strcmp(dot, ".jpeg") == 0 || strcmp(dot, ".gif") == 0) {
            file_node_create(headNode, dir_cont->d_name, path);
        }
    }
    closedir(dirp);
}

file_node_p file_node_init()
{
    file_node_p headNode = (file_node_p)malloc(sizeof(file_node_t));
    headNode->prev       = headNode;
    headNode->next       = headNode;
    strcpy(headNode->name, "head");
    strcpy(headNode->path, "head");

    findBMPByDir("res/img", headNode);
    // findBMPByDir("/res/imgc", headNode);
    return headNode;
}

void file_node_create(file_node_p headNode, char * name, char * path)
{
    file_node_p p = headNode;
    while(p->next != headNode) {
        p = p->next;
    }
    file_node_p newNode = (file_node_p)malloc(sizeof(file_node_t));

    strcpy(newNode->name, name);
    strcpy(newNode->path, path);
    // strcpy(newNode->path, NULL);
    strcat(newNode->path, "/");
    // printf("path:%s   name:%s\n", newNode->path, newNode->name);

    p->next        = newNode;
    newNode->prev  = p;
    newNode->next  = headNode;
    headNode->prev = newNode;
}

void print_file_node(file_node_p headNode)
{
    file_node_p p = headNode->next;
    while(p != headNode) {
        printf("name:%s\t path:%s\n", p->name, p->path);
        p = p->next;
    }
}

file_node_p find_file_node(file_node_p headNode, int currIMG)
{
    int i         = 0;
    file_node_p p = headNode->next;
    while(p != headNode) {
        if(i == currIMG) {
            return p;
        }
        i++;
        p = p->next;
    }
    return p;
}

int get_file_node_num(file_node_p headNode)
{
    int count     = 0;
    file_node_p p = headNode->next;
    while(p != headNode) {
        count++;
        p = p->next;
    }
    return count;
}

file_node_p get_img_path_by_index(file_node_p headNode, int index)
{
    int count     = get_file_node_num(headNode);
    index         = (index + count) % count;
    int i         = 0;
    file_node_p p = headNode->next;
    while(p != headNode) {
        if(i == index) {
            return p;
        }
        i++;
        p = p->next;
    }
    return NULL;
}

void free_file_node(file_node_p headNode)
{
    file_node_p p = headNode->next;
    while(p != headNode) {
        file_node_p tmp = p;
        p               = p->next;
        free(tmp);
    }
    free(headNode);
}